package com.simon.jkxj.ui.diet;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.simon.jkxj.R;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.formatter.ValueFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.simon.jkxj.ui.diet.BloodSugarDataManager;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class BloodSugarRecordActivity extends AppCompatActivity {
    private int addCount = 0;
    private TextView tvNormalCount;
    public static class BloodSugarRecord {
        public float value;
        public long time;
        public BloodSugarRecord(float value, long time) {
            this.value = value;
            this.time = time;
        }
    }
    // private List<BloodSugarRecord> recordList = new ArrayList<>(); // 注释掉本地List

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blood_sugar_record);
        ImageView btnAdd = findViewById(R.id.btn_add);
        tvNormalCount = findViewById(R.id.tv_normal_count);
        ImageView btnBack = findViewById(R.id.btn_back);
        if (btnBack != null) {
            btnBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BloodSugarRecordActivity.this, BloodSugarAddActivity.class);
                startActivityForResult(intent, 1001);
            }
        });
        updateChartAndStats();
        TextView tvDate = findViewById(R.id.tv_date);
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日", Locale.getDefault());
        String dateStr = dateFormat.format(new Date());
        tvDate.setText(dateStr);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK) {
            float value = data.getFloatExtra("blood_sugar_value", 0);
            long time = data.getLongExtra("blood_sugar_time", System.currentTimeMillis());
            BloodSugarDataManager.addRecord(new BloodSugarRecord(value, time));
            updateChartAndStats();
        }
    }

    private void updateChartAndStats() {
        List<BloodSugarRecord> recordList = BloodSugarDataManager.getRecords();
        // 1. 更新曲线图
        List<Entry> entries = new ArrayList<>();
        int high = 0, low = 0, normal = 0;
        float sum = 0f;
        // 获取当天零点的时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long todayZero = calendar.getTimeInMillis();
        for (int i = 0; i < recordList.size(); i++) {
            BloodSugarRecord r = recordList.get(i);
            float hour = (r.time - todayZero) / (60f * 60f * 1000f); // 0-24小时
            entries.add(new Entry(hour, r.value));
            sum += r.value;
            if (r.value > 6.1f) high++;
            else if (r.value < 3.9f) low++;
            else normal++;
        }
        LineChart chart = findViewById(R.id.line_chart);
        if (entries.size() > 0) {
            LineDataSet dataSet = new LineDataSet(entries, "血糖");
            dataSet.setCircleRadius(5f);
            dataSet.setLineWidth(2f);
            dataSet.setColor(0xFF8BC34A);
            dataSet.setCircleColor(0xFF8BC34A);
            dataSet.setValueTextSize(12f);
            LineData lineData = new LineData(dataSet);
            chart.setData(lineData);
        } else {
            chart.clear();
        }
        // 设置x轴 0-24小时，间隔4小时，显示0:00-24:00
        XAxis xAxis = chart.getXAxis();
        xAxis.setAxisMinimum(0f);
        xAxis.setAxisMaximum(24f);
        xAxis.setLabelCount(7, true);
        xAxis.setGranularity(4f);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int hour = (int) value;
                if (hour < 0) hour = 0;
                if (hour > 24) hour = 24;
                return String.format("%02d:00", hour);
            }
        });
        chart.getAxisLeft().setAxisMinimum(0f);
        chart.getAxisLeft().setAxisMaximum(20f);
        chart.getAxisLeft().setLabelCount(5, true);
        chart.getAxisRight().setEnabled(false);
        chart.invalidate();

        // 2. 更新统计项
        ((TextView)findViewById(R.id.tv_high_count)).setText(high + " 次");
        ((TextView)findViewById(R.id.tv_low_count)).setText(low + " 次");
        ((TextView)findViewById(R.id.tv_normal_count)).setText(normal + " 次");
        // 3. 平均值
        TextView tvAvg = findViewById(R.id.tv_avg);
        if (recordList.size() == 0) {
            tvAvg.setText("0 mmo/L");
        } else {
            float avg = sum / recordList.size();
            tvAvg.setText(String.format("%.1f mmo/L", avg));
        }
        // 4. 最新血糖值
        TextView tvValue = findViewById(R.id.tv_blood_sugar_value);
        TextView tvStatus = findViewById(R.id.tv_blood_sugar_status);
        TextView tvAdvice = findViewById(R.id.tv_diet_advice);
        View cardAdvice = findViewById(R.id.card_diet_advice);
        if (recordList.size() == 0) {
            tvValue.setText("0");
            tvStatus.setText("");
            cardAdvice.setVisibility(View.GONE);
        } else {
            float latest = recordList.get(recordList.size()-1).value;
            tvValue.setText(String.format("%.1f", latest));
            if (latest > 6.1f) {
                tvStatus.setText("偏高");
                tvStatus.setTextColor(0xFFE91E63);
                cardAdvice.setVisibility(View.VISIBLE);
                tvAdvice.setText("饮食建议：\n1. 控制主食总量，选择全谷物、杂粮等低升糖指数食物。\n2. 多吃新鲜蔬菜，适量摄入高纤维水果（如苹果、柚子）。\n3. 避免高糖、高脂肪、高热量食物，如甜点、油炸食品。\n4. 少量多餐，规律进食，避免暴饮暴食。\n5. 多饮水，限制含糖饮料和酒精摄入。");
            } else if (latest < 3.9f) {
                tvStatus.setText("偏低");
                tvStatus.setTextColor(0xFF03A9F4);
                cardAdvice.setVisibility(View.VISIBLE);
                tvAdvice.setText("饮食建议：\n1. 及时补充碳水化合物，如面包、米饭、糖果等。\n2. 避免空腹和长时间不进食，三餐定时，必要时加餐。\n3. 适当摄入富含蛋白质的食物，如牛奶、鸡蛋、豆制品。\n4. 外出时随身携带糖果或饼干，以备低血糖时应急。\n5. 避免饮酒，防止低血糖加重。");
            } else {
                tvStatus.setText("正常");
                tvStatus.setTextColor(0xFF4CAF50);
                cardAdvice.setVisibility(View.VISIBLE);
                tvAdvice.setText("饮食建议：\n1. 保持均衡饮食，主食、蔬菜、蛋白质合理搭配。\n2. 规律作息，适量运动，维持健康体重。\n3. 控制油盐糖摄入，预防血糖波动。\n4. 定期监测血糖，关注身体变化。");
            }
        }
        // 5. 目标范围文字
        TextView tvTarget = findViewById(R.id.tv_blood_sugar_target);
        tvTarget.setText("正常范围：3.9-6.1mmo/L");
    }
} 